//
//  CSJNetTools.swift
//  weibo
//
//  Created by 崔顺建 on 16/8/10.
//  Copyright © 2016年 cui. All rights reserved.
//

import UIKit
import AFNetworking
enum RequestType: Int {
    case GET = 0
    case POST = 1


}
//网络请求专用类
class CSJNetTools:AFHTTPSessionManager {
    //单例全局访问
    static let sharedTools: CSJNetTools = {
    let tools = CSJNetTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
    return tools
    }()
    
    func request(requestType: RequestType, url: String, parameters: AnyObject?, callBack: (response: AnyObject?,error: NSError?) -> ()) {
        if requestType == .GET {GET(url, parameters: parameters, progress: nil, success: { (_, response) -> Void in
            
            callBack(response: response, error: nil)
            }) { (_, error) -> Void in
             callBack(response: nil, error: error)
        }
        } else {
        
        POST(url, parameters: parameters, progress: nil, success: { (_, response) -> Void in
            callBack(response: response, error: nil)
            
            }, failure: { (_, error) -> Void in
                  callBack(response: nil, error: error)
        })
        
        }
    }
   
}
//首页相关接口
extension CSJNetTools {
//获取当前最新微博
    func requestNewStatus(accesstoken: String, maxId: Int64 ,sinceId: Int64 ,callback: (response: AnyObject?, error: NSError?) -> ()) {
    let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
    //参数
    let prams = ["access_token": accesstoken,
                 "max_id": "\(maxId)",
                "since_id": "\(sinceId)"
        ]
    
        //let path = url + "?access_token=" + accesstoken
        
       // print(path)
        
        request(.GET, url: url, parameters: prams, callBack: callback)
        
    
    }

}

//  OAuth登录相关接口
extension CSJNetTools {
     //  通过code获取accesstoken
    func getAccessToken(code: String, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        //获取网络
        let url = "https://api.weibo.com/oauth2/access_token"
        let prams = ["client_id": webAppKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_Uri ]
        
        
        request(.POST, url: url, parameters: prams, callBack: callBack)
    }
    //  通过accesstoken和uid获取用户信息
    func userMessage(userAccount: CSJUserAccount, callBack: (response: AnyObject?, error: NSError?) -> ()) {
        
        let url = "https://api.weibo.com/2/users/show.json"
        let parmas = ["access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        ]
        request(.GET, url: url, parameters: parmas, callBack: callBack)

}

}








